﻿// owner 蒋家伟

#include "WordReader.h"

// jsdk
#include "Dbg_Warn_Define.h"

using namespace jsdk;

jsdk::WordReader::~WordReader()
{
}

jsdk::OwnerPtr<jsdk::WordReader> jsdk::WordReader::create()
{
    OwnerPtr<jsdk::WordReader> opWordReader = NEW_AS_OWNERPTR(WordReader);
    DBG_WARN_AND_RETURN_NULLPTR_UNLESS(opWordReader, L"读取word对象创建失败", L"蒋家伟", L"2023-11-24");
    return transformOwnerShip(opWordReader);
}

bool jsdk::WordReader::openDocument(const std::wstring& fileName)
{
    if (fileName.empty())
        return false;
    m_doc.file(StringUtils::toString(fileName));
    if (!m_doc.open())
        return false;

    for (duckx::Table table = m_doc.tables(); table.has_next(); table = table.next())
    {
        m_tableCounts++;
    }
    return true;
}

bool jsdk::WordReader::openTable(uint64_t tableCount)
{
    if (tableCount > m_tableCounts)
        return false;

    for (m_currentTable = m_doc.tables(); m_currentTable.has_next(); m_currentTable = m_currentTable.next())
    {
        if (!(--tableCount))
        {
            return true;
        }
    }
    return true;
}

bool jsdk::WordReader::getCellData(uint64_t row, uint64_t col, std::wstring& res)
{
    res = {};
    DBG_WARN_AND_RETURN_FALSE_UNLESS(row > 0 && col > 0, L"行列值从1开始", L"蒋家伟", L"2023-11-25");
    duckx::TableRow currentRow;
    for (currentRow = m_currentTable.rows(); currentRow.has_next(); currentRow = currentRow.next())
    {
        if (!(--row))
        {
            break;
        }
    }

    DBG_WARN_AND_RETURN_FALSE_UNLESS(row == 0, L"行越界", L"蒋家伟", L"2023-11-26");

    duckx::TableCell currentCell;
    for (currentCell= currentRow.cells(); currentCell.has_next(); currentCell = currentCell.next())
    {
        if (!(--col))
        {
            break;
        }
    }

    DBG_WARN_AND_RETURN_FALSE_UNLESS(col == 0, L"列越界", L"蒋家伟", L"2023-11-26");

    for (duckx::Paragraph paragrah = currentCell.paragraphs(); paragrah.has_next(); paragrah = paragrah.next())
    {
        for (duckx::Run run = paragrah.runs(); run.has_next(); run = run.next())
        {
            res += StringUtils::toUTF8WString(run.get_text());
        }
        res += L'\n';
    }

    return true;
}

uint64_t jsdk::WordReader::getTableCount()
{
    return m_tableCounts;
}
